/*
 * Wave.java
 *
 * Created on November 25, 2007, 3:15 PM
 *
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package hextd.wave;

import com.twolattes.json.Entity;
import com.twolattes.json.Value;
import hextd.creep.Factory;
import hextd.creep.Creep;
import hextd.core.Context;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;

@Entity
public class Wave {

	private ArrayList<Creep> enemies = new ArrayList<Creep>();
	private boolean finalised = false;
	private Context context;
	private int owner = -1;
	private int level;
	private HashMap<EnemyInstance, Integer> enemyCounts = new HashMap<EnemyInstance, Integer>();
	@Value(name = "hp")
	public long baseHealth;
	@Value(name = "rw")
	public long baseReward;
	@Value(name = "sc", optional = true)
	public long baseScore;
	@Value(name = "crps")
	public List<List<String>> creeps;

	public class EnemyInstance implements Comparable<EnemyInstance> {

		public Factory.Enemy type;
		public Creep.Size size;
		public int price;
		public int score;
		public long health;

		public EnemyInstance(Factory.Enemy t, Creep.Size s, long h, int price, int score) {
			this.type = t;
			this.size = s;
			this.health = h;
			this.price = price;
			this.score = score;
		}

		@Override
		public int compareTo(EnemyInstance o) {
			if (o.type == this.type && o.size == this.size && o.price == this.price && o.score == this.score && o.health == this.health) {
				return 0;
			} else if (this.health > o.health) {
				return 1;
			} else {
				return -1;
			}
		}
	}

	public Wave() {
	}

	/** Creates a new instance of Wave */
	public Wave(long baseHealth, long basePrice, int owner) {
		this.baseHealth = baseHealth;
		this.baseReward = basePrice;
		this.baseScore = basePrice;
		this.owner = owner;
		creeps = new ArrayList<List<String>>();
	}

	/** Creates a new instance of Wave */
	public Wave(long baseHealth, long basePrice, int baseScore, int owner) {
		this.baseHealth = baseHealth;
		this.baseReward = basePrice;
		this.baseScore = baseScore;
		this.owner = owner;
		creeps = new ArrayList<List<String>>();
	}

	public void setContext(Context c) {
		context = c;
	}

	public void addEnemiesFromNames(String[] names) {
		creeps.add(Arrays.asList(names));
	}

	public void addEnemiesFromNames(String[] names, int path) {
		while (creeps.size() < path) {
			creeps.add(null);
		}
		creeps.add(Arrays.asList(names));
	}

	private void countEnemy(EnemyInstance e) {
		Integer i = null;
		for (EnemyInstance o : enemyCounts.keySet()) {
			if (o.compareTo(e) == 0) {
				i = enemyCounts.get(o);
				e = o;
				break;
			}
		}

		if (i == null) {
			i = new Integer(0);
		}
		i++;
		enemyCounts.put(e, i);
	}

	public Set<EnemyInstance> enemySet() {
		if (!this.finalised) {
			this.finalise();
		}
		return enemyCounts.keySet();
	}

	public int enemyCount(EnemyInstance e) {
		if (!this.finalised) {
			this.finalise();
		}
		Integer i = enemyCounts.get(e);
		if (i == null) {
			return 0;
		}
		return i.intValue();
	}

	public int enemyCount() {
		if (!this.finalised) {
			this.finalise();
		}
		return this.enemies.size();
	}

	private void finalise() {
		this.enemies.clear();
		this.enemyCounts.clear();
		EnemyInstance tempInstance;
		for (int path = 0; path < creeps.size(); path++) {
			List<String> names = creeps.get(path);
			if (names != null) {
				int nr = 1;
				int count = 0;
				float prefDel;
				float totDel = this.context.getPath(path).getBaseDelay();
				for (int i = 0; i < names.size(); i++) {
					String entry = names.get(i);
					String[] split = entry.split(" ");
					String name = "";
					if (split.length == 1) {
						name = split[0];
					} else {
						try {
							nr = Integer.parseInt(split[0]);
						} catch (NumberFormatException e) {
							System.out.println("Wave::finalise: Problem in wave " + baseHealth + " " + baseReward);
							System.out.println("Wave::finalise: Not a creeptype nor a numer on linepart: " + name);
							nr = 1;
						}
						name = split[1];
					}
					if (name.length() > 0) {
						if (Factory.isEnemy(name)) {
							Factory.Enemy type = Factory.identifyEnemy(name);
							Creep.Size s = Factory.getSize(name);

							double healthMod = 1;
							float delayMod = 1;
							int number;
							switch (s) {
								case large:
									number = Math.round(0.49f + ((float) nr) / 10f);
									healthMod = 1.0 * nr / number;
									delayMod = s.scaleMod;
									nr = number;
									break;
								case small:
									number = nr * 10;
									healthMod = 0.2;
									delayMod = 0.1f;
									nr = number;
									break;
							}
							int price;
							int score;
							if (baseReward > 0) {
								price = Math.max(1, (int) Math.round(baseReward * healthMod));
							} else if (baseReward == -1) {
								price = -1;
							} else {
								price = 0;
							}
							if (baseScore > 0) {
								score = Math.max(1, (int) Math.round(baseScore * healthMod));
							} else {
								score = 0;
							}
							long health = Math.round(this.baseHealth * healthMod);

							tempInstance = new EnemyInstance(type, s, health, price, score);
							this.countEnemy(tempInstance);

							// Now we generate the enemies.
							for (int e = 0; e < nr; e++) {
								int eCount = enemies.size();
								if (eCount > 0) {
									// The preffered delay is the maximum of that of this unit, and the unit before it.
									prefDel = delayMod * Math.max(Factory.identifyEnemy(name).getPreferredDelay(), enemies.get(eCount - 1).getPreferredDelay());
								} else {
									prefDel = delayMod * Factory.identifyEnemy(name).getPreferredDelay();
								}
								totDel += prefDel;
								enemies.add(Factory.getEnemy(name, this.context, this.owner, path, totDel, health, price, score));
								count++;
							}

							nr = 1;
						} else {
							try {
								nr = new Integer(name);
							} catch (NumberFormatException ex) {
								System.out.println("Wave::finalise: Problem in wave " + baseHealth + " " + baseReward);
								System.out.println("Wave::finalise: Not a creeptype nor a numer on linepart: " + name);
								nr = 1;
							}
						}
					}
				}
			}
			this.finalised = true;
		}
	}

	/*
	 * Clears the list of enemies to free up memory.
	 */
	public void clear() {
		this.enemies.clear();
		this.enemyCounts.clear();
		this.finalised = false;
	}

	public Collection<Creep> getEnemies() {
		this.finalise();
		Collection<Creep> retval = new ArrayList<Creep>(enemies);
		this.clear();
		return retval;
	}

	public long getBaseHealth() {
		return baseHealth;
	}

	public long getBasePrice() {
		return baseReward;
	}

	public long getBaseScore() {
		return baseScore;
	}

	/**
	 * @return the level this wave represents.
	 */
	public int getLevel() {
		return level;
	}

	/**
	 * @param level the level this wave represents
	 */
	public void setLevel(int level) {
		this.level = level;
	}
}
